import { http } from "@/utils/http";
import { baseUrlApi } from "@/api/utils";

type Result = {
  ok: boolean;
  msg: string;
  code: number;
  time: number;
  [key: string]: any;
};
/**
 * 查询
 * @param data
 */
export const get = (data?: object) => {
  return http.request<Result>("post", baseUrlApi("api/get"), { data });
};
/**
 * 新增
 * @param data
 */
export const post = (data?: object) => {
  return http.request<Result>("post", baseUrlApi("api/post"), { data });
};
/**
 * 修改
 * @param data
 */
export const put = (data?: object) => {
  return http.request<Result>("post", baseUrlApi("api/put"), { data });
};
/**
 * 单表查询
 * @param table 表名
 * @param query 查询条件
 * @param page 当前页
 * @param count 每页数量
 */
export const getTable = (
  table: string,
  query: object = {},
  page: number = 0,
  count: number = 10
) => {
  const data = {
    [`${table}[]`]: {
      [`${table}`]: { ...query },
      query: 2,
      page: page,
      count: count
    }
  };
  return http.request<Result>("post", baseUrlApi("api/get"), {
    data
  });
};

export const getList = (
  params: object,
  page: number = 0,
  count: number = 10
) => {
  const data = {
    "[]": {
      ...params,
      page: page,
      count: count,
      query: 2
    }
  };
  return http.request<Result>("post", baseUrlApi("api/get"), {
    data
  });
};

/**
 * 单表查询
 * @param table 表名
 * @param query 查询条件
 * @param page 当前页
 * @param count 每页数量
 */
export const findTable = (table: string, query: object = {}) => {
  const data = {
    [`${table}`]: { ...query }
  };
  return http.request<Result>("post", baseUrlApi("api/get"), {
    data
  });
};

/**
 * 新增表单
 * @param table 表名
 * @param params 数据
 */
export const postTable = (table: string, params: object) => {
  const data = {
    [`${table}`]: params
  };
  return http.request<Result>("post", baseUrlApi(`api/post/${table}`), {
    data
  });
};
/**
 * 更新表单
 * @param table 表名
 * @param params 数据
 */
export const putTable = (table: string, params: object) => {
  const data = {
    [`${table}`]: params
  };

  for (let key in params) {
    if (params.hasOwnProperty(key)) {
      const value = params[key];
      if (typeof value === "object" && value !== null) {
        params[key] = JSON.stringify(value);
      }
    }
  }
  return http.request<Result>("post", baseUrlApi(`api/put/${table}`), {
    data
  });
};
/**
 * 保存表单
 * @param table 表名
 * @param params 数据
 */
export const saveTable = (table: string, params: object) => {
  let url = `api/put/${table}`;
  if (params["id"] == null) {
    delete params["id"];
    url = `api/post/${table}`;
  }
  const data = {
    [`${table}`]: params
  };
  return http.request<Result>("post", baseUrlApi(url), {
    data
  });
};
/**
 * 删除表单
 * @param table 表名
 * @param params 数据
 */
export const delTable = (table: string, params: object) => {
  const data = {
    [`${table}`]: params
  };
  return http.request<Result>("post", baseUrlApi(`api/delete/${table}`), {
    data
  });
};
